const { checkAuth } = require('../../utils/auth.js')
const { getUserInfo, clearUserInfo } = require('../../utils/user.js')
const { getApiUrl } = require('../../config/config.js')
const app = getApp()

Page({
  data: {
    userInfo: null,
    unreadCount: 0,
    theme: 'light', // 主题模式
    refreshing: false, // 刷新状态
    stats: {
      myFans: 0,
      myFollows: 0,
      myPublish: 0,
      myPraised: 0,
      myCollection: 0
    },
    isLogin: false,
    // 标签相关
    showTagsEditor: false,
    editingTags: [],
    showAddTagInput: false,
    newTagValue: '',
    maxTagCount: 5, // 最大标签数量
    isSavingTags: false,
    // 默认标签选项
    defaultTagOptions: ['学习', '运动', '音乐', '美食', '游戏', '旅行', '电影', '阅读', '摄影', '编程']
  },

  onLoad() {
    // 获取当前主题
    const theme = wx.getStorageSync('theme') || 'light'
    this.setData({ theme })

    // 监听主题变更
    if (!wx.eventCenter) {
      // 如果eventCenter不存在，初始化它
      wx.eventCenter = {
        listeners: {},
        emit(event, data) {
          if (this.listeners[event]) {
            this.listeners[event].forEach(callback => callback(data))
          }
        },
        on(event, callback) {
          if (!this.listeners[event]) {
            this.listeners[event] = []
          }
          this.listeners[event].push(callback)
        },
        off(event, callback) {
          if (this.listeners[event]) {
            if (callback) {
              const index = this.listeners[event].indexOf(callback)
              if (index !== -1) {
                this.listeners[event].splice(index, 1)
              }
            } else {
              this.listeners[event] = []
            }
          }
        }
      }
    }
    
    wx.eventCenter.on('themeChanged', (theme) => {
      console.log('Theme changed to:', theme) // 添加日志
      this.setData({ theme })
    })

    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        userInfo,
        isLogin: true
      })
    }
  },

  onShow() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      this.setData({ 
        userInfo: null,
        isLogin: false 
      })
      return
    }
    
    // 格式化注册时间
    const formattedUserInfo = {
      ...userInfo,
      createTime: this.formatDate(userInfo.createTime)
    }
    
    // 确保gender字段有默认值
    if (formattedUserInfo.gender === undefined || formattedUserInfo.gender === null) {
      formattedUserInfo.gender = 1; // 默认为男性
    }
    
    this.setData({ 
      userInfo: formattedUserInfo,
      isLogin: true
    })
    this.loadUserStats()
  },

  // 格式化时间为年月日
  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  getUserInfo() {
    const userInfo = getUserInfo()
    if (userInfo) {
      // 格式化时间
      if (userInfo.createTime) {
        userInfo.createTime = this.formatTime(userInfo.createTime)
      }
      if (userInfo.updateTime) {
        userInfo.updateTime = this.formatTime(userInfo.updateTime)
      }
      // 处理个人简介的换行
      if (userInfo.biography) {
        userInfo.biography = userInfo.biography.replace(/\\n/g, '\n')
      }
      this.setData({ userInfo })
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({ refreshing: true })
    await this.getUserInfo()
    wx.stopPullDownRefresh()
    this.setData({ refreshing: false })
  },

  // 切换主题
  toggleTheme() {
    console.log('Toggle theme clicked') // 添加日志
    const newTheme = this.data.theme === 'light' ? 'dark' : 'light'
    app.globalData.theme = newTheme
    wx.setStorageSync('theme', newTheme)
    this.setData({ theme: newTheme })
    wx.eventCenter.emit('themeChanged', newTheme)
  },

  onTapEditProfile() {
    wx.navigateTo({
      url: '../edit_person/edit_person'
    })
  },

  onTapVerify() {
    wx.navigateTo({
      url: '../verify/verify'
    })
  },

  onTapMyPosts() {
    wx.navigateTo({
      url: '/pages/post_list/post_list?type=publish'
    })
  },

  onTapMyLikes() {
    wx.navigateTo({
      url: '/pages/post_list/post_list?type=like'
    })
  },

  onTapMyCollections() {
    wx.navigateTo({
      url: '/pages/post_list/post_list?type=collection'
    })
  },

  onTapNotification() {
    wx.switchTab({
      url: '../message/message'
    })
  },

  onTapSettings() {
    wx.showActionSheet({
      itemList: ['清除缓存', '关于我们','版本信息', '退出登录'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0: // 清除缓存
            wx.showModal({
              title: '提示',
              content: '确定要清除缓存吗？',
              success: (res) => {
                if (res.confirm) {
                  wx.clearStorage({
                    success: () => {
                      wx.showToast({
                        title: '清除成功',
                        icon: 'success'
                      })
                    }
                  })
                }
              }
            })
            break
          case 1: // 关于我们
            wx.showModal({
              title: '关于我们',
              content: '树岛是一款校园社交与信息交互平台，\n欢迎大家前来使用体验',
              showCancel: false
            })
            break
          case 2: // 版本信息
            wx.navigateTo({
              url: '/pages/update/update'
            })
            break
          case 3: // 退出登录
            this.onTapLogout()
            break
        }
      }
    })
  },

  onTapLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorage()
          wx.reLaunch({
            url: '../login/login'
          })
        }
      }
    })
  },

  // 加载用户统计数据
  async loadUserStats() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          // url: `http://localhost:8090/user/query/${this.data.userInfo.id}`,
          url: getApiUrl(`/user/query/${this.data.userInfo.id}`),
          method: 'GET',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        this.setData({
          stats: res.data.data
        })
      } else if (res.data.code === 401) {
        // token 失效时的处理
        wx.removeStorageSync('token')
        wx.removeStorageSync('userInfo')
        wx.redirectTo({
          url: '/pages/login/login'
        })
      }
    } catch (error) {
      console.error('Load user stats failed:', error)
    }
  },

  onUnload() {
    // 清除监听
    wx.eventCenter.off('themeChanged')
  },

  onTapMyFans() {
    wx.navigateTo({
      url: '/pages/user_list/user_list?type=fans'
    })
  },

  onTapMyFollows() {
    wx.navigateTo({
      url: '/pages/user_list/user_list?type=follows'
    })
  },

  // 跳转到用户列表页面
  navigateToUserList(e) {
    const type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: `/pages/user_list/user_list?type=${type}`
    })
  },
  
  // 跳转到帖子列表页面
  navigateToPostList(e) {
    const type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: `/pages/post_list/post_list?type=${type}`
    })
  },
  
  // 跳转到设置页面
  navigateToSettings() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    })
  },

  // 打开标签编辑器
  openTagsEditor() {
    if (!this.data.userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    // 复制当前标签到编辑数组
    const currentTags = this.data.userInfo.tags || [];
    this.setData({
      showTagsEditor: true,
      editingTags: [...currentTags],
      showAddTagInput: false,
      newTagValue: ''
    });
  },
  
  // 关闭标签编辑器
  closeTagsEditor() {
    this.setData({
      showTagsEditor: false
    });
  },
  
  // 阻止冒泡
  stopPropagation() {
    return;
  },
  
  // 移除标签
  removeTag(e) {
    const index = e.currentTarget.dataset.index;
    const editingTags = [...this.data.editingTags];
    editingTags.splice(index, 1);
    
    this.setData({
      editingTags
    });
  },
  
  // 显示添加标签输入框
  showAddTagInput() {
    this.setData({
      showAddTagInput: true,
      newTagValue: ''
    });
  },
  
  // 取消添加标签
  cancelAddTag() {
    this.setData({
      showAddTagInput: false,
      newTagValue: ''
    });
  },
  
  // 标签输入变化
  onTagInputChange(e) {
    this.setData({
      newTagValue: e.detail.value
    });
  },
  
  // 确认添加标签
  confirmAddTag() {
    const newTag = this.data.newTagValue.trim();
    if (!newTag) {
      wx.showToast({
        title: '标签不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 检查标签是否已存在
    if (this.data.editingTags.includes(newTag)) {
      wx.showToast({
        title: '标签已存在',
        icon: 'none'
      });
      return;
    }
    
    // 添加新标签
    const editingTags = [...this.data.editingTags, newTag];
    this.setData({
      editingTags,
      showAddTagInput: false,
      newTagValue: ''
    });
  },
  
  // 保存用户标签
  async saveUserTags() {
    if (this.data.isSavingTags) return;
    
    this.setData({ isSavingTags: true });
    
    try {
      const userId = this.data.userInfo.id;
      const tags = this.data.editingTags;
      
      // 发送请求保存标签
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl('/user/updateTags'),
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token')
          },
          data: {
            userId: userId,
            tags: tags
          },
          success: resolve,
          fail: reject
        });
      });
      
      if (res.data && res.data.code === 200) {
        // 更新成功，刷新用户信息
        const userInfo = this.data.userInfo;
        userInfo.tags = this.data.editingTags;
        
        // 更新本地存储
        wx.setStorageSync('userInfo', userInfo);
        
        this.setData({
          userInfo: userInfo,
          showTagsEditor: false
        });
        
        wx.showToast({
          title: '标签更新成功',
          icon: 'success'
        });
      } else {
        // 处理不同的错误情况
        let errorMsg = '标签更新失败';
        if (res.data?.code === 400) {
          errorMsg = res.data?.msg || '标签参数错误';
        } else if (res.data?.code === 500) {
          errorMsg = res.data?.msg || '服务器错误';
        }
        
        wx.showToast({
          title: errorMsg,
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('Save tags failed:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ isSavingTags: false });
    }
  },
  
  // 个人标签点击事件
  onTapTag(e) {
    const tag = e.currentTarget.dataset.tag;
    // 可以添加标签点击后的行为，例如搜索相同标签的用户
    console.log('Tag clicked:', tag);
  },

  // 选择默认标签
  selectDefaultTag(e) {
    const tag = e.currentTarget.dataset.tag;
    
    // 检查标签是否已存在
    if (this.data.editingTags.includes(tag)) {
      wx.showToast({
        title: '标签已存在',
        icon: 'none'
      });
      return;
    }
    
    // 检查是否已达到最大标签数
    if (this.data.editingTags.length >= this.data.maxTagCount) {
      wx.showToast({
        title: `最多添加${this.data.maxTagCount}个标签`,
        icon: 'none'
      });
      return;
    }
    
    // 添加标签
    const editingTags = [...this.data.editingTags, tag];
    this.setData({
      editingTags
    });
  }
}) 